package com.itlong.cloud.controller.sdkV1.cloud.intercom.app;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkSDKServerUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.common.network.ITCPServiceClient;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudTalkErrorCodeEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppOldServeServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      云对讲SDK服务控制器
 * </desc>
 *
 * @createDate 2018/05/14
 */
@Controller
@RequestMapping("/cloud/interface")
public class CloudTalkSDKAppServeController {
    //日志记录对象
    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkSDKAppServeController.class);

    @Autowired
    IAppOldServeServiceClient iAppOldServeServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    ITCPServiceClient itcpServiceClient;

    @Value("${" + PlatformConstants.APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;

    @Value("${" + PlatformConstants.CLOUD_TALK_SDK_AESKEY + "}")
    private  String cloudTalkSdkAesKey; //AES加密KEY
    @Value("${" + PlatformConstants.CLOUD_TALK_SDK_MD5KEY + "}")
    private  String cloudTalkSdkMd5Key;  //MD5加密KEY

    /**
     * <desc>
     *    云对讲SDK_获取SDK版本
     * </desc>
     *
     * @param type 应用接入凭证
     * @param sort 应用接入密钥
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/05/14
     */
    @ResponseBody
    @RequestMapping("/app/version")
    public Message getLatestApp(String type, String sort){
        try {
            if (StringUtils.isEmpty(type) || StringUtils.isEmpty(sort)){
                return  new Message(Code.NOT_PARAM);
            }
            Message message = iAppOldServeServiceClient.getLatestApp(type,sort);
            return message;
        } catch (Exception e) {
            LOG.error(String.format("【云对讲SDK_APP_检测SDK版本】{type:%s sort:%s} exception:{%s}", type,sort,e));
            return new Message(Code.ERROR);
        }
    }

    /**
     * <desc>
     *      SDK开发者认证
     * </desc>
     *
     * @param appid 应用接入凭证
     * @param secret 应用接入密钥
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2018/11/20
     */
    @ResponseBody
    @RequestMapping("/app/getToken")
    public Object getToken(String appid, String secret){
        try {
            if(StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //登陆校验及缓存更新
            CloudTalkSDKServerUserCacheVO userCacheVO = iCloudTalkSDKServerUserServiceClient.sdkAppLogin(appid, secret);
            if (userCacheVO == null) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_DEVELOP_ERR.getErrorCode());
            }
            JSONObject js = new JSONObject();
            js.put("token", userCacheVO.getToken());

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK APP端认证_CloudTalkSDKAppServeController_getToken】APP端SDK认证异常", e);
        }
    }

    /**
     * <desc>
     *      请求参数进行加密
     * </desc>
     *
     * @return
     * @author Juguang.S
     * @createDate 2018/11/27
     */
    @PostMapping(path = "/app/paramsEncryption")
    @ResponseBody
    public Object paramsEncryption(){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            Map<String,String[]> map = (Map<String, String[]>) request.getParameterMap();
            Map<String,String> mapresult = new HashMap<>();
            for (String str : map.keySet()) {
                //map.keySet()返回的是所有key的值
                String[] strresult = map.get(str);//得到每个key多对用value的值
                StringBuffer sb = new StringBuffer();

                for(int i = 0;i<strresult.length;i++){
                    sb.append(strresult[i]);        //append String并不拥有该方法，所以借助StringBuffer
                }
                mapresult.put(str,sb.toString());
            }
            String encryptResult = DesEncryptUtil.aesEncrypt(JsonUtil.toJSON(mapresult), cloudTalkSdkAesKey, cloudTalkSdkMd5Key);

/*            String plusEncode = URLEncoder.encode("+", "UTF-8");
            encryptResult.replaceAll("\\+", plusEncode);*/

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("encrypScript", encryptResult);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),resultMap);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK】请求参数进行加密失败",e);
        }
    }

    /**
     * <desc>
     *      返回结果进行解密
     * </desc>
     *
     * @return
     * @author Juguang.S
     * @createDate 2018/11/27
     */
    @PostMapping(path = "/app/responseDecrypt")
    @ResponseBody
    public Object responseDecrypt(){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            Map<String,String[]> map = (Map<String, String[]>) request.getParameterMap();

            String content= StringHandlerUtil.replaceBlank(map.get("encrypScript")[0].toString().substring(0, map.get("encrypScript")[0].toString().length() - 32));
            String encryptResult = URLDecoder.decode(DesEncryptUtil.aesDecrypt(content, cloudTalkSdkAesKey), "UTF-8");
            Map<String,Object> params = JsonUtil.toObject(encryptResult,HashMap.class);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),params);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK】返回结果进行解密失败",e);
        }
    }

}
